package top.bigdata.service.request;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;

@Slf4j
public final class HttpInterface {
    public static LinkedHashMap get(String url) {
        // 创建HttpClient对象
        var httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        // 创建GetMethod对象
        var getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String response;
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK){
                log.error("请求出错：{}", getMethod.getStatusLine());
            }

            //读取HTTP响应内容
            var inputStream = getMethod.getResponseBodyAsStream();
            var responseBody = inputStream.readAllBytes();
            response = new String(responseBody, StandardCharsets.UTF_8);

            var objectMapper = new ObjectMapper();
            return objectMapper.readValue(response, LinkedHashMap.class);
        } catch (IOException e) {
            log.error("请求{}发生异常", url);
            throw new RuntimeException(e);
        } finally {
            getMethod.releaseConnection();
        }
    }
}
